<template>
  <div>
    <el-card style="margin: 20px 0px">
      <CategorySelect
        @getCategoryID="getCategoryID"
        :show="!isShowTable"
      ></CategorySelect>
    </el-card>
    <el-card>
      <div v-show="isShowTable">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3ID"
          style="margin: 10px 0px"
          @click="addAttr"
          >添加属性</el-button
        >
        <el-table :data="attrList" style="width: 100%" border>
          <el-table-column
            label="序号"
            width="80px"
            type="index"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150px">
          </el-table-column>
          <el-table-column prop="prop" label="属性值列表">
            <template slot-scope="{ row, $index }">
              <el-tag
                type="success"
                v-for="(attrValue, index) in row.attrValueList"
                :key="attrValue.id"
                style="margin: 0px 20px"
                >{{ attrValue.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150px" align="center">
            <template slot-scope="{ row, $index }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="updateAttr(row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加或者修改属性的结构 -->
      <div v-show="!isShowTable">
        <el-form ref="form" label-width="80px" :inline="true" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              v-model="attrInfo.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttrValue"
          :disabled="!attrInfo.attrName"
          >添加属性值
        </el-button>
        <el-button @click="isShowTable = true">取消</el-button>

        <el-table
          style="width: 100%; margin: 20px 0px"
          border
          :data="attrInfo.attrValueList"
        >
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="80px"
          >
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称">
            <template slot-scope="{ row, $index }">
              <!-- 这里需要将span和input进行来回的切换,核心思想是给attrValueList中的每一个对象
              都添加一个flag属性,从而独立实现各个对象之间的查看与编辑 -->
              <el-input
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                size="mini"
                v-if="row.flag"
                @blur="toLook(row)"
                @keyup.native.enter="toLook(row)"
                :ref="$index"
              ></el-input>
              <span
                v-else
                @click="toEdit(row, $index)"
                style="display: block"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作">
            <template slot-scope="{ row, $index }">
              <el-popconfirm
                :title="`确定要删除${row.valueName}吗?`"
                @onConfirm="deleteAttrValue(row, $index)"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  slot="reference"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="addOrUpdateAttr"
          :disabled="attrInfo.attrValueList.length < 1"
          >保存</el-button
        >
        <el-button @click="isShowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "Attr",
  data() {
    return {
      category1ID: "",
      category2ID: "",
      category3ID: "",
      attrList: [],
      // 控制table表格的显示与隐藏
      isShowTable: true,
      // 收集新增属性|修改属性使用的
      attrInfo: {
        // 属性名
        attrName: "",
        // 存储属性值
        attrValueList: [],
        // 三级分类的ID
        categoryID: 0,
        // 用来区分几级ID
        categoryLevel: 3,
      },
    };
  },
  methods: {
    async addOrUpdateAttr() {
      // 上传给服务器之前需要整理参数
      // 1.为空的属性值需要过滤掉
      // 2.提交的数据中不应该包含flag字段
      // filter函数:返回一个新的数组,item为数组中的每一项
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(
        (item) => {
          if (item.valueName != "") {
            delete item.flag;
            return true;
          }
        }
      );
      try {
        await this.$API.Attr.reqAddOrUpdateAttr(this.attrInfo);
        this.$message.success("保存成功");
        this.getAttrList();
        this.isShowTable = true;
      } catch (error) {
        this.$message.error("保存失败");
      }
    },
    deleteAttrValue(row, index) {
      this.attrInfo.attrValueList.splice(index, 1);
    },
    toEdit(row, index) {
      row.flag = true;
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    // 由编辑模式切换为查看模式,这里的row指的是添加的最新数据
    toLook(row) {
      // 防止用户输入的属性值为空
      if (row.valueName.trim() == "") {
        this.$message.error("属性值不能为空");
        return "属性值为空";
      }
      let isRepeat = this.attrInfo.attrValueList.some((item) => {
        if (item !== row) {
          return row.valueName == item.valueName;
        }
      });
      if (isRepeat) {
        this.$message.error("属性值重复");
        return;
      }
      row.flag = false;
    },
    updateAttr(row) {
      this.isShowTable = false;
      // 这里需要使用到深拷贝,使用浅拷贝无法解决点击取消按钮后数据依然被更改的问题
      this.attrInfo = cloneDeep(row);
      // 向响应式对象中添加一个 property，并确保这个新 property 同样是响应式的，且触发视图更新。
      // 它必须用于向响应式对象上添加新 property，因为 Vue 无法探测普通的新增 property
      this.attrInfo.attrValueList.forEach((element) => {
        // 参数1:要添加属性的对象
        // 参数2:添加的属性名
        // 参数3:添加的属性值
        this.$set(element, "flag", false);
      });
    },
    addAttr() {
      this.isShowTable = false;
      // 清除数据,防止点击添加属性时出现数据回显的问题
      this.attrInfo = {
        // 属性名
        attrName: "",
        // 存储属性值
        attrValueList: [],
        // 三级分类的ID
        categoryID: this.category3ID,
        // 用来区分几级ID
        categoryLevel: 3,
      };
    },
    // 点击添加属性值按钮才往数组里追加对象是因为如果一开始就在attrInfo.attrValueList中内置一个对象,那么
    // 点击添加属性按钮时表格会自动出来一个el-input,而设计的要求是输完属性名后才可以添加属性值
    addAttrValue() {
      this.attrInfo.attrValueList.push({
        // 属性名ID
        attrId: this.attrInfo.id,
        // 属性值
        valueName: "",
        // 给每一个属性值添加一个标记,用于切换查看模式和编辑模式
        flag: true,
      });
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus();
      });
    },
    getCategoryID({ categoryID, level }) {
      if (level == 1) {
        this.category1ID = categoryID;
        this.category2ID = "";
        this.category3ID = "";
      } else if (level == 2) {
        this.category2ID = categoryID;
        this.category3ID = "";
      } else {
        this.category3ID = categoryID;
        this.getAttrList();
      }
    },
    async getAttrList() {
      const { category1ID, category2ID, category3ID } = this;
      let result = await this.$API.Attr.reqAttrList(
        category1ID,
        category2ID,
        category3ID
      );
      if (result.code == 200) {
        this.attrList = result.data;
        return "ok";
      } else {
        return Promise.reject(new Error("failure"));
      }
    },
  },
};
</script>

<style scoped>
</style>
